const express = require('express');
const db = require('../config/db');
const { authenticateToken } = require('../middleware/auth');
const { io } = require('../server'); // 导入Socket.io实例
const router = express.Router();

// 获取消息列表
router.get('/messages', authenticateToken, async (req, res) => {
  try {
    const { page = 1, pageSize = 10, type, status } = req.query;
    const offset = (page - 1) * pageSize;
    
    // 管理员可以看到所有消息，普通用户只能看到发送给自己的消息
    let query = 'SELECT id, sender_id, sender_name, receiver_id, receiver_name, title, content, type, status, created_at FROM messages WHERE 1=1';
    let countQuery = 'SELECT COUNT(*) as total FROM messages WHERE 1=1';
    const params = [];
    
    // 普通用户只能查看发送给自己的消息
    if (req.user.role !== 'admin') {
      query += ' AND (receiver_id = ? OR receiver_id IS NULL)';
      countQuery += ' AND (receiver_id = ? OR receiver_id IS NULL)';
      params.push(req.user.id);
    }
    
    // 添加类型筛选
    if (type) {
      query += ' AND type = ?';
      countQuery += ' AND type = ?';
      params.push(type);
    }
    
    // 添加状态筛选
    if (status) {
      query += ' AND status = ?';
      countQuery += ' AND status = ?';
      params.push(status);
    }
    
    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(pageSize));
    params.push(parseInt(offset));
    
    const [rows] = await db.execute(query, params);
    const [countResult] = await db.execute(countQuery, params.slice(0, -2));
    const total = countResult[0].total;
    
    res.json({
      code: 200,
      message: '获取消息列表成功',
      data: {
        list: rows,
        pagination: {
          currentPage: parseInt(page),
          pageSize: parseInt(pageSize),
          total: total
        }
      }
    });
  } catch (error) {
    console.error('获取消息列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 发送消息（仅管理员）
router.post('/messages', authenticateToken, async (req, res) => {
  try {
    // 只有管理员可以发送消息
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        code: 403,
        message: '权限不足，只有管理员可以发送消息'
      });
    }
    
    const { receiver_id, receiver_name, title, content, type = 'personal' } = req.body;
    
    // 参数验证
    if (!title || !content) {
      return res.status(400).json({
        code: 400,
        message: '标题和内容不能为空'
      });
    }
    
    // 插入数据库
    const [result] = await db.execute(
      'INSERT INTO messages (sender_id, sender_name, receiver_id, receiver_name, title, content, type) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [req.user.id, req.user.name, receiver_id || null, receiver_name || null, title, content, type]
    );
    
    const messageId = result.insertId;
    
    // 获取插入的消息详情
    const [rows] = await db.execute(
      'SELECT id, sender_id, sender_name, receiver_id, receiver_name, title, content, type, status, created_at FROM messages WHERE id = ?',
      [messageId]
    );
    
    const message = rows[0];
    
    // 通过Socket.io推送消息（添加错误处理）
    try {
      if (receiver_id) {
        // 发送给特定用户
        io.emit('newMessage', { 
          ...message, 
          targetUser: receiver_id 
        });
      } else {
        // 广播给所有用户
        io.emit('newMessage', { 
          ...message, 
          targetUser: 'all' 
        });
      }
    } catch (socketError) {
      console.error('Socket.io推送消息失败:', socketError);
      // 即使推送失败，也不影响消息发送成功
    }
    
    res.status(201).json({
      code: 201,
      message: '消息发送成功',
      data: message
    });
  } catch (error) {
    console.error('发送消息失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 标记消息为已读
router.put('/messages/:id/read', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    
    // 更新消息状态为已读
    const [result] = await db.execute(
      'UPDATE messages SET status = ? WHERE id = ? AND (receiver_id = ? OR receiver_id IS NULL)',
      ['read', id, req.user.id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({
        code: 404,
        message: '消息不存在或无权限操作'
      });
    }
    
    res.json({
      code: 200,
      message: '消息标记为已读成功'
    });
  } catch (error) {
    console.error('标记消息为已读失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 删除消息
router.delete('/messages/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    
    // 管理员可以删除任何消息，普通用户只能删除发送给自己的消息
    let query = 'DELETE FROM messages WHERE id = ?';
    const params = [id];
    
    if (req.user.role !== 'admin') {
      query += ' AND receiver_id = ?';
      params.push(req.user.id);
    }
    
    const [result] = await db.execute(query, params);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({
        code: 404,
        message: '消息不存在或无权限操作'
      });
    }
    
    res.json({
      code: 200,
      message: '消息删除成功'
    });
  } catch (error) {
    console.error('删除消息失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

module.exports = router;